package com.hehe.library.activity;

import android.content.Intent;

import android.os.Bundle;

import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;


import com.hehe.library.MyBook;
import com.hehe.library.R;

import org.json.JSONException;
import org.json.JSONObject;


import java.io.IOException;

import io.realm.Realm;
import io.realm.RealmQuery;

public class AddBooksActivity extends AppCompatActivity{

    boolean isNextActivate = false;
    EditText mNameET;
    EditText mIntroET;
    EditText mAuthorET;
    EditText mNumET;
    EditText mIdET;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        intiView();


    }



    private void intiView() {
        setContentView(R.layout.activity_add_books);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_add);
        setSupportActionBar(toolbar);

        mNameET = (EditText) findViewById(R.id.name_add);
        mIntroET = (EditText) findViewById(R.id.intro_add);
        mAuthorET = (EditText) findViewById(R.id.author_add);
        mNumET = (EditText) findViewById(R.id.num_add);
        mIdET = (EditText) findViewById(R.id.id_add);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_add, menu);
        return super.onCreateOptionsMenu(menu);
    }
String name;
    String intro;
    String author;
    String num;
    String id;
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //若昵称不为空,则可执行修改
        name = mNameET.getText().toString();
        intro = mIntroET.getText().toString();
        author = mAuthorET.getText().toString();
        num = mNumET.getText().toString();
        id = mIdET.getText().toString();
        if(!name.isEmpty()&&!intro.isEmpty()&&!author.isEmpty()&&!num.isEmpty()&&!id.isEmpty()) {//四个内容都已填写
            attemptAdd();
        }
        return super.onOptionsItemSelected(item);
    }

    private void attemptAdd() {
        Realm realm= Realm.getDefaultInstance();
        realm.beginTransaction();//开始传输
        MyBook book = realm.createObject(MyBook.class);
        book.setBookname(name);
        book.setBookintro(intro);
        book.setBookauthor(author);
        book.setBooknum(num);
        book.setBookid(id);
        realm.commitTransaction();
        Toast.makeText(getApplicationContext(),"图书添加成功",Toast.LENGTH_SHORT).show();
        finish();
        Intent intent = new Intent(AddBooksActivity.this,MainActivity.class);
        startActivity(intent);
    }


}
